package com.aiti.myproject.server;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.client.Window;

import com.aiti.myproject.shared.UploadImage;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
		@SuppressWarnings("deprecation")
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
		BlobKey blobKey = blobs.get("image");
		if (null != blobKey) {
			ImagesService imageService = ImagesServiceFactory
					.getImagesService();
			@SuppressWarnings("deprecation")
			String imageUrl = imageService.getServingUrl(blobKey);

			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
			Entity uploadedImage = new Entity("UploadImage");
			uploadedImage.setProperty("blobKey", blobKey);
			uploadedImage.setProperty(UploadImage.CREATE_AT, new Date());
			uploadedImage.setProperty(UploadImage.OWNER_ID, user.getUserId());
			uploadedImage.setUnindexedProperty(UploadImage.SERVING_URL,
					imageUrl);

			DatastoreService datastoreService = DatastoreServiceFactory
					.getDatastoreService();
			datastoreService.put(uploadedImage);

			String keyString = KeyFactory.keyToString(uploadedImage.getKey());
			resp.sendRedirect("/upload?uploadedImageKey=" + keyString);
		} else {
			Window.alert("Something wrong here!");
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		String imageUrl = req.getParameter("uploadedImageKey");
		resp.setHeader("Content-Type", "text/html");
		resp.getWriter().println(imageUrl);
	}

}
